package org.taobao.ibatiside.ui.pref;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.connectivity.ProfileManager;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPropertyPage;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.PropertyPage;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import org.taobao.ibatiside.ui.Activator;

public class BatisProjectSettingPage extends PropertyPage implements IWorkbenchPropertyPage {
	public static final String CONNECTION="connection";
	public static final String TEMPLATES_SRC="tplsrc";
	private ComboViewer comboViewer;
	private Text text;
	/**
	 * Create the property page.
	 */
	public BatisProjectSettingPage() {
		setTitle("iBATIS Project");
	}

	private void setProjectPreferenceStore() {
		IProject current_project = (IProject) getElement().getAdapter(IProject.class);		
		ProjectScope scope = new ProjectScope(current_project);
		setPreferenceStore(new ScopedPreferenceStore(scope, Activator.PLUGIN_ID));
	}

	/**
	 * Create contents of the property page.
	 * @param parent
	 */
	@Override
	public Control createContents(Composite parent) {
		setProjectPreferenceStore();
		final IProject proj = (IProject) getElement().getAdapter(IProject.class);
		
		Composite container = new Composite(parent, SWT.NULL);
		container.setLayout(new GridLayout(2, false));
		
		Label lblConnection = new Label(container, SWT.NONE);
		lblConnection.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblConnection.setText("Connection ");
		
		IConnectionProfile[] profiles = ProfileManager.getInstance().getProfiles(true);
		
		comboViewer = new ComboViewer(container, SWT.NONE);
		Combo combo = comboViewer.getCombo();
		combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		Label lblTemplateSourceFolder = new Label(container, SWT.NONE);
		lblTemplateSourceFolder.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		lblTemplateSourceFolder.setText("Template Source Folder");
		
		Button btnBrowse = new Button(container, SWT.NONE);
		btnBrowse.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
				dialog.setTitle("Template Folder");
				dialog.setMessage("Select a folder which stores jet templates.");
				dialog.setAllowMultiple(false);
				String last_tpl_src = getPreferenceStore().getString(TEMPLATES_SRC);
				if (StringUtils.isNotBlank(last_tpl_src)){
					IResource res = proj.findMember(last_tpl_src);
					if (res != null){
						dialog.setInitialSelection(res);
					}
				}
				dialog.addFilter(new ViewerFilter() {
					
					@Override
					public boolean select(Viewer viewer, Object parentElement, Object element) {
						return element instanceof IFolder;
					}
				});
				dialog.setInput(proj);
				if (dialog.open() == ElementTreeSelectionDialog.OK){
					IFolder folder = (IFolder) dialog.getFirstResult();
					String proj_rel_path = folder.getProjectRelativePath().toString();
					text.setText(proj_rel_path);
				}
			}
		});
		btnBrowse.setText("Browse...");
		
		text = new Text(container, SWT.BORDER);
		text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		comboViewer.setContentProvider(new ArrayContentProvider());
		comboViewer.setLabelProvider(new LabelProvider(){
			@Override
			public String getText(Object element) {
				IConnectionProfile profile = (IConnectionProfile) element;
				return profile.getName()+"("+profile.getDescription()+")";
			}
		});
		comboViewer.setInput(profiles);
		String connection_setting = getPreferenceStore().getString(CONNECTION);
		IConnectionProfile connection_profile = null;
		if (StringUtils.isNotBlank(connection_setting)){
			if ((connection_profile = ProfileManager.getInstance().getProfileByName(connection_setting)) != null){
				comboViewer.setSelection(new StructuredSelection(connection_profile), true);
			}else{
				setMessage(connection_setting+" can't point to a valid connection, please check!!");
			}
		}
		String last_tpl_src = getPreferenceStore().getString(TEMPLATES_SRC);
		text.setText(last_tpl_src);
		return container;
	}
	@Override
	protected void performApply() {
		if (comboViewer != null && !comboViewer.getControl().isDisposed()){
			IConnectionProfile selected = (IConnectionProfile) ((IStructuredSelection)comboViewer.getSelection()).getFirstElement();
			if (selected != null){
				getPreferenceStore().putValue(CONNECTION, selected.getName());
			}
		}
		if (text != null && !text.isDisposed()){
			getPreferenceStore().putValue(TEMPLATES_SRC, text.getText().trim());
		}
		super.performApply();
	}
}
